﻿using Modules.CheckIn;
using Modules.Project;
using Modules.Reports;
using PmSoft.Caching.Redis;
using PmSoft.Quartz;
using Quartz;

namespace ManagementApi.Jobs;

/// <summary>
/// 人员考勤天数及工时统计
/// </summary>
[DisallowConcurrentExecution]//不可并行执行
[JobDescription("0 0 00 * * ?")]//必须每天0点执行,并且只能执行一次，统计昨日数据
//[JobDescription("0 */1 * * * ?")]//测试1分钟执行1次
public class GenerateCheckinWorkHoursJob : IJob
{
    private readonly CheckinWorkHoursService checkinWorkHoursService;
    private readonly ReportProjectGroupDaysService reportProjectGroupDaysService;
    private readonly PmSoftRedisCache redisCache;
    private readonly ILogger logger;

    public GenerateCheckinWorkHoursJob(CheckinWorkHoursService checkinWorkHoursService,
        ReportProjectGroupDaysService reportProjectGroupDaysService,
        PmSoftRedisCache redisCache,
        ILogger<GenerateCheckinWorkHoursJob> logger)
    {
        this.checkinWorkHoursService = checkinWorkHoursService;
        this.redisCache = redisCache;
        this.reportProjectGroupDaysService = reportProjectGroupDaysService;
        this.logger = logger;
    }

    /// <summary>
    /// 执行
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task Execute(IJobExecutionContext context)
    {

        //昨日
        DateTime date = DateTime.Now.AddDays(-1);

        #region 班组成员考勤按月统计
        IEnumerable<int> memberIds;
        while ((memberIds = checkinWorkHoursService.GetMemberIdsInNoUpdate(date)).Count() > 0)
        {
            try
            {
                checkinWorkHoursService.Generate(memberIds, date);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "人员考勤每日更新月报表生成失败");
                throw;
            }
        }

        #region 注释掉的
        //1.查询所有昨日考勤记录
        //DateTime checkinDate = DateTime.Now.AddDays(-1).Date;
        ////DateTime checkinDate = Convert.ToDateTime("2024-03-04");//测试指定日期数据
        //string month = checkinDate.ToString("yyyyMM");
        //IEnumerable<CheckInDetail> checkInDetails = checkinDetailService.GetCheckInDetailsByMonthAndCheckDate(month, checkinDate);
        //IEnumerable<int> memberIds = checkInDetails.Select(a => a.MemberId).Distinct();
        //IEnumerable<CheckinWorkHours> checkinWorkHours = checkinWorkHoursService.GetCheckinWorkHoursByMonthAndMemberIds(month, memberIds);
        //IEnumerable<ProjectGroupMember> projectGroupMembers = projectGroupMemberService.GetProjectGroupMembersByMemberIds(memberIds);
        //foreach (var item in memberIds)
        //{
        //    ProjectGroupMember? member = projectGroupMembers.FirstOrDefault(a => a.Id == item);
        //    if (member != null)
        //    {
        //        CheckInDetail? inCheckindetail = checkInDetails.OrderBy(a => a.CreateTime).FirstOrDefault(a => a.MemberId == item && a.EntryExitMark == 进出标识.进场);
        //        CheckInDetail? outCheckindetail = checkInDetails.OrderByDescending(a => a.CreateTime).FirstOrDefault(a => a.MemberId == item && a.EntryExitMark == 进出标识.出场);
        //        CheckinWorkHours? workHours = checkinWorkHours.FirstOrDefault(a => a.MemberId == item);
        //        if (workHours == null)
        //        {//新增
        //            workHours = new()
        //            {
        //                MemberId = member.Id,
        //                Month = month,
        //                ProjectId = member.ProjectId,
        //                PersonId = member.PersonId,
        //                GroupId = member.GroupId,
        //                CheckinDay = 1,
        //                CreateTime = DateTime.Now,
        //                LastUpdateTime = DateTime.Now
        //            };
        //            if (inCheckindetail != null && outCheckindetail != null)
        //            {
        //                workHours.WorkHours = Convert.ToDecimal((outCheckindetail.CreateTime - inCheckindetail.CreateTime).TotalHours);
        //                checkinWorkHoursService.Create(workHours);
        //            }
        //            else if (inCheckindetail != null || outCheckindetail != null)
        //            {
        //                workHours.WorkHours = 0;
        //                checkinWorkHoursService.Create(workHours);
        //            }
        //        }
        //        else
        //        {
        //            //修改
        //            workHours.CheckinDay++;
        //            workHours.LastUpdateTime = DateTime.Now;
        //            if (inCheckindetail != null && outCheckindetail != null)
        //            {
        //                workHours.WorkHours = workHours.WorkHours + Convert.ToDecimal((outCheckindetail.CreateTime - inCheckindetail.CreateTime).TotalHours);
        //                checkinWorkHoursService.Update(workHours);
        //            }
        //            else if (inCheckindetail != null || outCheckindetail != null)
        //            {
        //                checkinWorkHoursService.Update(workHours);
        //            }
        //        }
        //        if (inCheckindetail != null || outCheckindetail != null)
        //            redisCache.HashSet($"checkin_work_hours:{month}", $"memberId:{item}", workHours);
        //    }
        //} 
        #endregion

        #endregion

        #region 统计项目每日统计

        IEnumerable<int> projectIds;
        while ((projectIds = reportProjectGroupDaysService.GetProjectIdsInNoUpdate(date)).Count() > 0)
        {
            foreach (int id in projectIds)
            {
                try
                {
                    reportProjectGroupDaysService.Generate(id, date);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "项目考勤日报表生成失败");
                    throw;
                }
            }
        }

        #region 注释掉的
        //1.查询当前项目状态是否为非完工
        //IEnumerable<ProjectInfo> projectInfos = projectService.GetAll().Where(a => a.PrjStatus != 项目状态.完工);
        //IEnumerable<ProjectGroupMember> groupMembers = projectGroupMemberService.GetProjectGroupMembersByProjectIds(projectInfos.Select(a => a.ProjectId));

        //foreach (var item in projectInfos)
        //{
        //    ReportProjectGroupDays projectGroupDays = new()
        //    {
        //        ProjectId = item.ProjectId,
        //        Date = checkinDate,
        //        CreateTime = DateTime.Now
        //    };

        //    if (item.PrjStatus != 项目状态.在建)
        //        projectGroupDays.NumberAttendees = 0;
        //    else
        //        projectGroupDays.NumberAttendees = groupMembers.Where(a => a.ProjectId == item.ProjectId && a.Status == 进出场状态.进场).Count();

        //    projectGroupDays.ActualAttendance = checkInDetails.Where(a => a.ProjectId == item.ProjectId).Select(a => a.PersonId).Distinct().Count();
        //    projectGroupDays.AbnormalNumberPeople = Math.Abs(projectGroupDays.NumberAttendees - projectGroupDays.ActualAttendance);
        //    reportProjectGroupDaysService.Create(projectGroupDays);
        //} 
        #endregion

        #endregion

        return Task.CompletedTask;
    }
}